<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import axios from 'axios';
/**
 * 定义props类型
 */
defineProps<{
    name: string
}>()
const keyword = ref<string>("");

const support = ref<string>("技术支持：汉吉健康");
/**
 *  商品列表源数据
 */
const itemListSource = ref<ItemDto[]>([]);
/**
 * 商品列表
 */
const itemList = ref<ItemDto[]>([]);
/**
 * 特惠商品
 */
const special_offer = ref<string>("");
/**
 * 是否正在加载中
 */
const loading = ref<boolean>(false);
/**
 * 是否有错误
 */
const isError = ref<boolean>(false);
/**
 * 错误信息
 */
const errorMsg = ref<string>("");

onMounted(async () => {
    // 处理商品列表数据
    await coverItemList();
});

//商品列表数据处理 
async function coverItemList() {
    loading.value = true;
    await getDataApiAsync().then(res => {
        itemListSource.value = res.data.data;
        itemList.value = res.data.data;
        //不利于测试
        // special_offer.value = getCheapestItem(itemList.value)?.name || "";
        //利于测试的写法
        var cheapestItem = getCheapestItem(itemList.value);
        if (cheapestItem != null) {
            special_offer.value = cheapestItem.name;
        }
        loading.value = false;
        isError.value = false;
        errorMsg.value = "";
    }).catch(err => {
        isError.value = true;
        errorMsg.value = err.message;
        loading.value = false;
    }).finally(() => {
        loading.value = false;
    });
}
//获取商品列表接口
async function getDataApiAsync() {
    return await axios.get('https://dev-1300222288.cos.ap-shanghai.myqcloud.com/JIJI/list.json', { params: { page: 1, size: 10, date: new Date().getTime() } })
}

/**
 * 获取商品的总价 computed
 */
const totalPriceComputed = computed(() => {
    return itemList.value.map(item => item.price).reduce((acc, cur) => acc + cur, 0);
});

/**
 * 获取商品的平均价 computed
 */
const averagePriceComputed = computed(() => {
    const total = totalPriceComputed.value; // 获取总价
    const count = itemList.value.length; // 获取商品数量
    // return count > 0 ? total / count : 0; // 计算均价，避免除以零
    if (count === 0) {
        return 0;
    } else {
        return total / count;
    }
});

/**
 * 获取特惠商品(价格最低的商品)
 * @param data 商品列表
 * @returns 价格最低的商品
 */
function getCheapestItem(data: ItemDto[]): ItemDto | null {

    if (data.length === 0) return null; // 如果列表为空，返回null

    return data.reduce((prev, curr) => {
        return (prev.price < curr.price) ? prev : (prev.price === curr.price ? prev : curr); // 返回价格较低的商品
    });
}
/**
 *  搜索商品列表
 */
function searchItemList() {
    itemList.value = itemListSource.value.filter(item => item.name.includes(keyword.value));
}

defineExpose({
    coverItemList,
    keyword,
    support,
    itemList,
    special_offer,
    loading,
    isError,
    errorMsg,
    itemListSource,
    totalPriceComputed,
    averagePriceComputed,
    getCheapestItem,
    getDataApiAsync,
    searchItemList
}); 
</script>

<template>
    <div class="greetings">

        <h3 class="green">欢迎来到{{ name }}</h3>
        <div style="border: 1px solid #ccc; padding: 10px;">
            <h2 v-if="loading">加载中.....</h2>
            <h2 v-else-if="isError">errorMsg：{{ errorMsg }}</h2>
            <div v-else>
                <div style="display: flex;">
                    <div style="width: 80%;">
                        <input style="line-height: 24px; width: 100%;" v-model="keyword" type="text"
                            placeholder="请输入项目名称">
                    </div>
                    <div>
                        <button style="line-height: 24px; margin-left: 4px; cursor: pointer;"
                            @click="searchItemList">搜索</button>
                    </div>
                </div>
                <ul style="padding-top: 12px;">
                    <li v-for="item in itemList" :key="item.id">
                        {{ item.name }} - ￥{{ item.price }}
                    </li>
                </ul>
                <p v-if="itemList.length === 0">没有找到项目</p>
                <div style="display: flex;">
                    <h3 class="hy-h3" style=" padding-right: 30px;">总价: ￥{{ totalPriceComputed }}</h3>
                    <h3 class="hy-h3">均价: ￥{{ averagePriceComputed }}</h3>
                </div>
                <div style="display: flex;">
                    <h3 class="hy-h3" style=" padding-right: 30px;">项目数量: {{ itemList.length }}种</h3>
                    <h3 class="hy-h3">特惠项目: {{ special_offer }}</h3>
                </div>
            </div>
        </div>
        <p style="text-align: right;padding-top: 6px;color: #999;">
            {{ support }}
        </p>
    </div>
</template>

<style scoped>
.green {
    color: green;
}

.greetings {
    padding: 20px;
    width: 400px;
    border-radius: 8px;
    background-color: #ffffff;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
}

.hy-h3 {
    border-top: 1px solid #ccc;
    margin-top: 20px;
    padding-top: 10px;
    font-weight: bold;
    font-size: 18px;
}

h1 {
    font-weight: 600;
    font-size: 2.5rem;
    position: relative;
    top: -10px;
    text-align: center;
    color: #333;
}

h3 {
    font-size: 1.5rem;
    color: #555;
}

.item-container {
    margin-top: 20px;
}

.item {
    list-style-type: none;
    margin: 10px 0;
    padding: 10px;
    background-color: #f9f9f9;
    border-radius: 5px;
    box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
}

.error-msg {
    color: red;
    text-align: center;
}

@media (min-width: 1024px) {

    .greetings h1,
    .greetings h3 {
        text-align: left;
    }
}
</style>
